# coding: utf-8

from leancloud import Object
from leancloud import File
from leancloud import Query
from leancloud import LeanCloudError
from leancloud import User
from flask import request
from datetime import datetime
import time
import os
from werkzeug.utils import secure_filename
from util.GainData import GainData
import json


class FarmerSayItem(Object):
    pass


class CommentSay():
    def __init__(self):
        pass

    # 添加评论
    def add(self):
        name = request.json['name']
        toReplyName = request.json['toReplyName']
        content = request.json['content']
        objectId = request.json['objectId']
        try:
            query = Query(FarmerSayItem)
            farmerSayItem = query.get(objectId)
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                farmerSayItem = None
            else:
                raise e

        commentStr = farmerSayItem.get('comments')
        if commentStr == None:
            comments = []
        else:
            comments = eval(commentStr)
        gaindata = GainData()
        avatar = gaindata.gainAvatar(name)
        toReplyAvatar = gaindata.gainAvatar(toReplyName)

        comment = {}
        comment['name'] = name
        comment['avatar'] = avatar
        comment['toReplyName'] = toReplyName
        comment['toReplyAvatar'] = toReplyAvatar
        comment['content'] = content
        time_now = long(time.time() * 1000)
        comment['time'] = time_now
        comments.append(comment)
        farmerSayItem.set('comments', str(comments))
        farmerSayItem.save()

        data = {'code': 200, "state": "success","time":time_now}
        return json.dumps(data, indent=1)
        pass

    # 删除评论
    def delete(self):
        commentTime = request.json['time']
        objectId = request.json['objectId']
        try:
            query = Query(FarmerSayItem)
            farmerSayItem = query.get(objectId)
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                farmerSayItem = None
            else:
                raise e

        commentStr = farmerSayItem.get('comments')
        if commentStr == None:
            comments = []
        else:
            comments = eval(commentStr)
        for comment in comments:
            if comment.get('time') == commentTime:
                comments.remove(comment)
        farmerSayItem.set('comments', str(comments))
        farmerSayItem.save()
        data = {'code': 200, "state": "success"}
        return json.dumps(data, indent=1)
        pass
